package sk.patt.eshop;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebApplication;

import sk.patt.eshop.data.dao.interfaces.BrandDao;
import sk.patt.eshop.data.dataobjects.Brand;

public class BrandsProvider extends SortableDataProvider {

	class SortableDataProviderComparator implements Comparator<Brand>, Serializable {
		public int compare(final Brand o1, final Brand o2) {
			PropertyModel<Comparable> model1 = new PropertyModel<Comparable>(o1, getSort().getProperty());
			PropertyModel<Comparable> model2 = new PropertyModel<Comparable>(o2, getSort().getProperty());

			int result = model1.getObject().compareTo(model2.getObject());

			if (!getSort().isAscending()) {
				result = -result;
			}

			return result;
		}

	}
	
	private List<Brand> list;
	private SortableDataProviderComparator comparator = new SortableDataProviderComparator();
	
	public BrandsProvider(BrandDao brandDao) {
		setSort("title", true);
		list = brandDao.findAll();
	}
	
	public Iterator iterator(final int first, final int count) {
		List<Brand> newList = new ArrayList<Brand>(list);

		// Sort the data
		Collections.sort(newList, comparator);

		// Return the data for the current page - this can be determined only after sorting
		return newList.subList(first, first + count).iterator();
	}

	public int size() {
		return list.size();
	}

	public IModel model(final Object object) {
		return new AbstractReadOnlyModel<Brand>() {
		 	@Override
			public Brand getObject() {
				return (Brand) object;
			}
		};
	}

}
